﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.IO;

namespace GenerateLoopStringTool
{
    public partial class MainForm : Form
    {
        private String manualString = @"说明：
{index}:行号
{n}:第n个参数(n从0开始)
{F1Upper:n}:第n个参数首字母大写
{F1Lower:n}:第n个参数首字母小写
{Upper:n}:第n个参数转换为大写
{Lower:n}:第n个参数转换为小写
";

        public MainForm()
        {
            InitializeComponent();
        }


        private void MainForm_Load(object sender, EventArgs e)
        {
            this.Text = this.Text + " v" + this.GetType().Assembly.GetName().Version.ToString();
            txtOutputFolder.Text = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
            txtResult.Text = manualString;
            EncodingInfo[] encodingInfoArray = Encoding.GetEncodings();
            cbFileEncoding.Items.AddRange(encodingInfoArray);
            cbFileEncoding.DisplayMember = "Name";

            for (int i = 0; i <= encodingInfoArray.Length - 1; i++)
            {
                if (encodingInfoArray[i].Name == "utf-8")
                {
                    cbFileEncoding.SelectedIndex = i;
                    break;
                }
            }
        }

        private void btnSelectOutputFolder_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog fbd = new FolderBrowserDialog();
            fbd.Description = "请选择输出目录:";
            var dr = fbd.ShowDialog();
            if (dr == System.Windows.Forms.DialogResult.Cancel)
                return;
            txtOutputFolder.Text = fbd.SelectedPath;
        }

        private void rbLoopVar_CheckedChanged(object sender, EventArgs e)
        {
            foreach (Control ctl in gbLoopVar.Controls)
            {
                if (ctl is Panel)
                    ctl.Enabled = false;
            }

            if (rbNumber.Checked)
                pnlNumber.Enabled = true;
            else if (rbCustomer.Checked)
                pnlCustomer.Enabled = true;
        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            try
            {
                //文件名模板
                String fileNameTemplate = txtFileNameTemplate.Text;
                //输出目录
                String outputFolderPath = txtOutputFolder.Text.Trim();
                //编码信息
                EncodingInfo fileEncodingFile = (EncodingInfo)cbFileEncoding.SelectedItem;
                //是否包括BOM
                Boolean isIncludeBOM = cbIncludeBOM.Checked;

                //模板文本
                String templateString = txtTemplateString.Text;
                List<String> loopVarList = new List<string>();
                if (rbNumber.Checked)
                {
                    Int32 startNumber = Int32.Parse(txtNumberStart.Text.Trim());
                    Int32 endNumber = Int32.Parse(txtNumberEnd.Text.Trim());
                    Int32 step = Int32.Parse(txtNumberStep.Text.Trim());

                    for (int i = startNumber; (step > 0 && i <= endNumber) || (step < 0 && i >= endNumber); i = i + step)
                    {
                        loopVarList.Add(i.ToString());
                    }
                }
                else if (rbCustomer.Checked)
                {
                    loopVarList.AddRange(txtCustomer.Lines);
                }
                //生成数据
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i <= loopVarList.Count - 1; i++)
                {
                    String currentLine = replaceVar(templateString, loopVarList[i], i);



                    //输出文件
                    if (rbGenToTextBox.Checked)
                        sb.AppendLine(currentLine);
                    else if (rbGenToFiles.Checked)
                    {
                        String fileName = replaceVar(fileNameTemplate, loopVarList[i], i);
                        String fileFullName = Path.Combine(outputFolderPath, fileName);

                        Encoding fileEncoding = fileEncodingFile.GetEncoding();                        
                        //如果不包括BOM头
                        if (!isIncludeBOM)
                        {
                            if (fileEncodingFile.Name == "utf-8")
                                fileEncoding = new UTF8Encoding(false);
                        }
                        
                        File.WriteAllText(fileFullName, currentLine, fileEncoding);
                    }

                    //显示进度
                    Int32 preProgress = pbProgress.Value;
                    Int32 currentProgress = (i + 1) * 100 / loopVarList.Count;
                    pbProgress.Value = currentProgress;
                    if (preProgress != currentProgress)
                    {
                        Thread.Sleep(10);
                        Application.DoEvents();
                    }
                }
                //输出数据
                if (rbGenToTextBox.Checked)
                    txtResult.Text = sb.ToString();
                else
                {
                    txtResult.Text = "生成成功";
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        //替换变量
        private String replaceVar(String templateString, String varLine, Int32 index)
        {
            String[] varArray = varLine.Split(new Char[] { '\t' });

            //替换{index}            
            String tmpLine = templateString.Replace("{index}", (index + 1).ToString());

            while (true)
            {
                if (tmpLine.Contains("{F1Upper:"))
                {
                    for (int i = 0; i <= varArray.Length - 1; i++)
                    {
                        String var = varArray[i];
                        String val = "";
                        if (!String.IsNullOrEmpty(var))
                        {
                            val = var.Substring(0, 1).ToUpper();
                            if (var.Length > 1)
                                val += var.Substring(1);
                        }
                        tmpLine = tmpLine.Replace(String.Format("{{F1Upper:{0}}}", i), val);
                    }
                    continue;
                }
                else if (tmpLine.Contains("{F1Lower:"))
                {
                    for (int i = 0; i <= varArray.Length - 1; i++)
                    {
                        String var = varArray[i];
                        String val = "";
                        if (!String.IsNullOrEmpty(var))
                        {
                            val = var.Substring(0, 1).ToLower();
                            if (var.Length > 1)
                                val += var.Substring(1);
                        }
                        tmpLine = tmpLine.Replace(String.Format("{{F1Lower:{0}}}", i), val);
                    }
                    continue;
                }
                else if (tmpLine.Contains("{Upper:"))
                {
                    for (int i = 0; i <= varArray.Length - 1; i++)
                    {
                        String var = varArray[i];
                        String val = var.ToUpper();
                        tmpLine = tmpLine.Replace(String.Format("{{Upper:{0}}}", i), val);
                    }
                    continue;
                }
                else if (tmpLine.Contains("{Lower:"))
                {
                    for (int i = 0; i <= varArray.Length - 1; i++)
                    {
                        String var = varArray[i];
                        String val = var.ToLower();
                        tmpLine = tmpLine.Replace(String.Format("{{Lower:{0}}}", i), val);
                    }
                    continue;
                }
                break;
            }

            //替换{n}
            return String.Format(tmpLine, varArray);
        }
    }
}
